package com.itheima.leyou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.leyou.mapper.SpecParamMapper;
import com.itheima.leyou.po.SpecGroup;
import com.itheima.leyou.po.SpecParam;
import com.itheima.leyou.service.SpecGroupService;
import com.itheima.leyou.service.SpecParamService;
import com.itheima.leyou.service.SpuDetailService;
import com.itheima.leyou.service.SpuService;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecParamServiceImpl extends ServiceImpl<SpecParamMapper, SpecParam>implements SpecParamService {

    @Autowired
    private SpuService spuService;

    @Autowired
    private SpuDetailService spuDetailService;

    @Autowired
    private SpecGroupService specGroupService;


    /**
     * 根据分类id查询规格参数组及组内信息
     * @param categoryId
     * @return
     */
    @Override
    public List<SpecGroupDTO> listSpecGroup(Long categoryId) {

        List<SpecGroupDTO> specGroupDTOS = SpecGroupDTO.convertEntityList(
                this.query()
                        .eq("category_id", categoryId)
                        .list());


        //key groupId,value,相同groupId对应的规格参数集合
        Map<Long, List<SpecParamDTO>> specParaMap = SpecParamDTO.convertEntityList(
                this.query()
                        .eq("category_id", categoryId)
                        .list())
                .stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        //循环给每个组赋值组内规格参数集合
        specGroupDTOS.forEach(specGroupDTO -> {
            specGroupDTO.setParams(specParaMap.get(specGroupDTO.getId()));
        });
        return specGroupDTOS;
    }



    @Override
    public List<SpecParamDTO> querySpecParam(Long categoryId,Long groupId, Boolean searching) {
        List<SpecParamDTO> specParamDTOS = SpecParamDTO.convertEntityList(this.query()
                .eq(null != categoryId, "category_id", categoryId)
                .eq(null != groupId, "group_id", groupId)
                .eq(null != searching, "searching", searching)
                .list());

        return specParamDTOS;

    }

    @Override
    public void addParam(SpecParamDTO paramDTO) {
        this.save(paramDTO.toEntity(SpecParam.class));
    }

    @Override
    public void updateParam(SpecParamDTO paramDTO) {
        this.updateById(paramDTO.toEntity(SpecParam.class));
    }
}
